package com.ruix.app.ui.stratum.setting;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.util.Base64;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.BitmapTypeRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.facebook.drawee.view.SimpleDraweeView;
import com.ruix.app.R;
import com.ruix.app.RuiApplication;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.mapper.ApiMapper;
import com.ruix.app.model.ClassDetail;
import com.ruix.app.model.Classes;
import com.ruix.app.model.WXShare;
import com.ruix.app.network.ApiConstant;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.ui.app.PhotoViewActivity;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.util.LogUitl;
import com.ruix.app.util.QRCodeDecoder;
import com.ruix.app.util.QRCodeEncoder;
import com.ruix.app.util.ShareUtil;
import com.ruix.app.util.ToastUtil;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil;
import io.reactivex.disposables.Disposable;

/**
 * Created by hadexs on 2017/4/25.
 */

public class ClassShareActivity extends BaseActivity implements View.OnClickListener{

    public static Intent newIntent(Context context, Classes classes, ClassDetail classDetail){
        Intent intent = new Intent(context,ClassShareActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("classes",classes);
        bundle.putSerializable("classDetail",classDetail);
        intent.putExtras(bundle);
        return intent;
    }

    private Classes currentClasses;
    private ClassDetail classDetail;
//    private SimpleDraweeView barCodeView;
    private ImageView  barCodeView;
    private TextView classNameView;
    private String classcodeurl;
    private String classlogourl;
    private LinearLayout contentView;

    @Override
    protected int loadViewLayout() {
        return R.layout.activity_class_share;
    }


    @Override
    protected void initView() {
        setTitle("圈子二维码");
        barCodeView = (ImageView) findViewById(R.id.sdv_barcode_view);
        classNameView = (TextView) findViewById(R.id.tv_class_name);
        contentView =  (LinearLayout)findViewById(R.id.ll_content_view);

        //todo
    }

    @Override
    protected void initLocalData() {
        Intent intent = getIntent();
        if (intent != null) {
            currentClasses = (Classes) intent.getSerializableExtra("classes");
            classDetail = (ClassDetail) intent.getSerializableExtra("classDetail");
            if (classDetail != null) {
                if (classDetail.isTeacherFriendCircle()) { //
                    classcodeurl = RuiXConstant.WX_TEACHE_FREAND_CIRECLE_SHARE + classDetail.getEncryptId();//&source=android&is_show_bottombar=1
                } else {
                    classcodeurl = RuiXConstant.WX_CLASS_INFO_URL + classDetail.getEncryptId();
                }
            }

            if (currentClasses != null) {
                classlogourl = currentClasses.getIcon();
                classNameView.setText(currentClasses.getName());
                buildBarcode();
            }
        }
    }

    private void loadBarcode(){
        String value = ApiConstant.API_CLASS_BARCODE + currentClasses.getID();
        barCodeView.setImageURI(Uri.parse(value));
        //tood

    }


    @Override
    protected void initListener() {
        findViewById(R.id.btn_save_barcode).setOnClickListener(this);
        findViewById(R.id.ll_share_to_circle).setOnClickListener(this);
        findViewById(R.id.ll_share_to_wechat).setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_save_barcode:
                saveBarcode();

                break;
            case R.id.ll_share_to_wechat:
                shareShit(true);

                break;
            case R.id.ll_share_to_circle:
                shareShit(false);

                break;
        }

    }

    private void buildBarcode(){
        if (!TextUtils.isEmpty(classlogourl)){
            Glide.with(RuiApplication.getAppContext()).load(classlogourl).asBitmap().into(new SimpleTarget<Bitmap>(80,80){

                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    createChineseQRCodeWithLogo(resource);
                }
            });
        } else {
            createChineseQRCode();
        }
    }

    private void createChineseQRCodeWithLogo(final Bitmap bitmap) {
        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... params) {
                return QRCodeEncoder.syncEncodeQRCode(classcodeurl, BGAQRCodeUtil.dp2px(ClassShareActivity.this, 200), Color.BLACK, Color.WHITE,bitmap);
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                if (bitmap != null) {
                    barCodeView.setImageBitmap(bitmap);
                }
            }
        }.execute();
    }


    private void createChineseQRCode() {
        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... params) {
                return QRCodeEncoder.syncEncodeQRCode(classcodeurl, BGAQRCodeUtil.dp2px(ClassShareActivity.this, 200));
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                if (bitmap != null) {
                    barCodeView.setImageBitmap(bitmap);
                }
            }
        }.execute();
    }


    private void saveBarcode(){
        contentView.setDrawingCacheEnabled(true);
        contentView.buildDrawingCache();  //启用DrawingCache并创建位图
        Bitmap bitmap = Bitmap.createBitmap(contentView.getDrawingCache()); //创建一个DrawingCache的拷贝，因为DrawingCache得到的位图在禁用后会被回收
        contentView.setDrawingCacheEnabled(false);
        saveImageToGallery(getApplicationContext(),bitmap);
    }



    public  void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        if (!checkCameraPermission()){
            return;
        }

        File appDir = new File(Environment.getExternalStorageDirectory(), "ruixue_barcode");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
//        try {
//            MediaStore.Images.Media.insertImage(context.getContentResolver(),
//                    file.getAbsolutePath(), fileName, null);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        String path = file.getAbsolutePath();
        Uri uri = Uri.fromFile(file);
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        //
        ToastUtil.showNewSuccessMsg("保存成功");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private void shareShit(boolean firend) {
        if (currentClasses == null){
            return;
        }

        String title = String.format("[%s]很不错哦！推荐给你～", currentClasses.getName());
        String content = "大家一起学以致用吧";//classDetail.getBenifite();

        String webUrl;
        if (classDetail.isTeacherFriendCircle()) { //
            webUrl = RuiXConstant.WX_TEACHE_FREAND_CIRECLE_SHARE + classDetail.getEncryptId();//&source=android&is_show_bottombar=1
        } else {
            webUrl = RuiXConstant.WX_CLASS_INFO_URL + classDetail.getEncryptId();
        }

        if (firend) {
            ShareUtil.shareToTimeline(this,currentClasses.getIcon(),webUrl, title, content, null);
        } else {
            ShareUtil.shareToSession(this,currentClasses.getIcon(),webUrl, title, content, null);
        }
    }


    public boolean checkCameraPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int aPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED || aPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(ClassShareActivity.this, new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

}
